﻿/*
 * 2010-5-19 16:38:10.
 *
 *  liuxing@91huayi.com
 */
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Web.UI;
using System.Text.RegularExpressions;
using System.Reflection;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Web;

namespace JKF.Substructure
{
    public static class ExtMethod
    {
        #region 基础类型扩展

        public static string ToShortDateLineFormat(this DateTime dt)
        {
            return dt.ToString("yyyy-MM-dd");
        }
        public static string ToShortDateLineFormat(this DateTime? dt)
        {
            return dt.HasValue ? dt.Value.ToString("yyyy-MM-dd") : "";
        }
        public static string ToFullDateTimeFormat(this DateTime? dt)
        {
            return dt.HasValue ? dt.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
        }
        public static string ToFullDateTimeFormat(this DateTime dt)
        {
            return dt.ToString("yyyy-MM-dd HH:mm:ss");
        }
        /// <summary>
        /// Convert data to string if null return ""
        /// </summary>
        /// <param name="it"></param>
        /// <returns></returns>
        public static string ToStringNoValue(this int? it)
        {
            return it.HasValue ? it.ToString() : "";
        }
        /// <summary>
        /// Convert data to string if null return ""
        /// </summary>
        /// <param name="it"></param>
        /// <returns></returns>
        public static string ToStringNoValue(this decimal? it)
        {
            return it.HasValue ? it.ToString() : "";
        }

        public static Guid ToGuid(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return Guid.Empty;
            }
            return new Guid(str);
        }

        public static Guid ToGuid(this byte[] bytes)
        {
            return new Guid(bytes);
        }

        public static bool In<T>(this T obj, IEnumerable<T> arr) where T : class
        {
            return arr.AsQueryable().Contains(obj);
        }

        public static void Action<T>(this IEnumerable<T> scource, Action<T> predicate)
        {
            foreach (var t in scource)
            {
                predicate(t);
            }
        }
        public static void Action<T>(this IEnumerable<T> scource, Action<int, T> predicate)
        {
            var i = 0;
            foreach (var t in scource)
            {
                predicate(i++, t);
            }
        }

        public static string ToGuidString(this byte[] bytes)
        {
            return bytes == null ? string.Empty : new Guid(bytes).ToString();
        }

        public static string ToMD5(this string str)
        {
            return StTool.MD5(str);
        }

        public static string FilterJs(this string str)
        {
            str = str.Replace("\\", "\\\\");
            str = str.Replace("\r", "\\r");
            str = str.Replace("\n", "\\n");
            str = str.Replace("'", "\\'");
            str = str.Replace("\"", "\\\"");
            str = str.Replace("\t", "\\t");
            str = str.Replace("\f", "\\f");
            str = str.Replace("\b", "\\b");
            return str;
        }

        /// <summary>
        /// 是否是GUID是则返回1
        /// </summary>
        /// <param name="strArgu"></param>
        /// <returns></returns>
        public static string IsGuid(this string strArgu)
        {
            return string.IsNullOrEmpty(strArgu) ? "0" : Regex.IsMatch(strArgu, "^[0-9a-z]{8}(-[0-9a-z]{4}){3}-[0-9a-z]{12}$", RegexOptions.IgnoreCase) ? "1" : "0";
        }
        /// <summary>
        /// 是否是Guid
        /// </summary>
        /// <param name="strArgu"></param>
        /// <returns></returns>
        public static bool IsGuidB(this string strArgu)
        {
            return !string.IsNullOrEmpty(strArgu) && (Regex.IsMatch(strArgu, "^[0-9a-z]{8}(-[0-9a-z]{4}){3}-[0-9a-z]{12}$", RegexOptions.IgnoreCase));
        }
        /// <summary>
        /// 是否是身份证号码
        /// </summary>
        /// <param name="strArg"></param>
        /// <returns></returns>
        public static bool IsIdNo(this string strArg)
        {
            return !string.IsNullOrEmpty(strArg) &&
                   (Regex.IsMatch(strArg, "^(([0-9x]{15})|([0-9x]{18}))$", RegexOptions.IgnoreCase));
        }

        public static void AddInParameterGuid(this Database db, DbCommand cmd, string name, string sysguid)
        {
            db.AddInParameter(cmd, name, DbType.Guid, sysguid.ToGuid());
        }

        /// <summary>
        /// 多维数组 降1维
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="lst"></param>
        /// <returns></returns>
        public static IEnumerable<T> MergeList<T>(this IEnumerable<List<T>> lst) where T : class,new()
        {

            foreach (var a in lst)
            {
                foreach (var b in a)
                {
                    yield return b;
                }
            }
        }

        public static int ToInt32(this string str)
        {
            return ToInt32(str, 0);
        }

        public static int ToInt32(this string str, int ifError)
        {
            int s;
            if (int.TryParse(str, out s))
            {
                return s;
            }
            else
            {
                return ifError;
            }
        }

        /// <summary>
        /// 通过对象属性,输出格式化的字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static string ToString2(this object obj, string format)
        {
            Type type = obj.GetType();
            PropertyInfo[] properties = type.GetProperties(
               BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance);

            MatchEvaluator evaluator = match =>
            {
                string propertyName = match.Groups["Name"].Value;
                PropertyInfo property = properties.FirstOrDefault(p => p.Name == propertyName);
                if (property != null)
                {
                    object propertyValue = property.GetValue(obj, null);
                    if (propertyValue != null) return propertyValue.ToString();
                    else return "";
                }
                else return match.Value;
            };
            return Regex.Replace(format, @"\[(?[^\]]+)\]", evaluator, RegexOptions.Compiled);
        }

        /// <summary>
        /// 转换成oracle的guid字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToOracelGuid(this Guid str)
        {
            return StTool.Guid2OraString(str);
        }

        /// <summary>
        /// 空字符串 直接返回
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToOracelGuid(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return str;
            }
            return StTool.Guid2OraString(str);
        }

        public static string Join(this IEnumerable<string> strs, string sp)
        {
            return string.Join(sp, strs.ToArray());
        }

        /// <summary>
        /// 返回 yyyy-MM-dd 的形式
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string Format(this DateTime dt)
        {
            return dt.ToString(SysConfig.DateFormat);
        }

        /// <summary>
        /// 本年 第一天
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string First(this DateTime dt)
        {
            dt = new DateTime(dt.Year, 1, 1);
            return dt.ToString(SysConfig.DateFormat);
        }

        /// <summary>
        /// 本年最后1天
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string Last(this DateTime dt)
        {
            dt = new DateTime(dt.Year, 12, 31);
            return dt.ToString(SysConfig.DateFormat);
        }

        public static DateTime ToDateTime(this string str)
        {
            DateTime dt;
            if (DateTime.TryParse(str, out dt))
            {
                return dt;
            }
            else
            {
                return DateTime.Now;
            }
        }

        public static decimal ToDecimal(this string str)
        {
            decimal s;
            if (decimal.TryParse(str, out s))
            {
                return s;
            }
            else
            {
                return (decimal)0;
            }
        }

        /// <summary>
        /// 将简单类,序列化
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson(this object obj)
        {
            SFWS.XJSON.Core.JsonSerializer jss = new SFWS.XJSON.Core.JsonSerializer();
            //System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            return jss.Serialize(obj);
        }

        /// <summary>
        /// 过滤字符串,防止sql注入
        /// </summary>
        /// <param name="text"></param>
        /// <param name="maxLength"></param>
        /// <returns></returns>
        public static string ToSqlString(this string text, int maxLength)
        {
            text = text.Trim();
            if (string.IsNullOrEmpty(text))
                return string.Empty;
            if (text.Length > maxLength)
                text = text.Substring(0, maxLength);
            text = Regex.Replace(text, "[\\s]{2,}", " ");	//two or more spaces
            text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n");	//<br>
            text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " ");	//&nbsp;
            text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty);	//any other tags
            text = text.Replace("'", "''");
            return text;
        }

        #endregion

        #region 控件扩展

        public static ListControl BindSource(this ListControl lc, IEnumerable source, string text, string val)
        {
            lc.DataSource = source;
            lc.DataTextField = text;
            lc.DataValueField = val;
            lc.DataBind();
            return lc;
        }

        /// <summary>
        /// HTML select 绑定扩展
        /// </summary>
        /// <param name="hs">绑定控件</param>
        /// <param name="source">数据源</param>
        /// <param name="text">显示文本</param>
        /// <param name="value">值</param>
        /// <returns>绑定后的控件</returns>
        public static HtmlSelect BindSource(this HtmlSelect hs, IEnumerable source, string text, string value)
        {
            hs.DataSource = source;
            hs.DataTextField = text;
            hs.DataValueField = value;
            hs.DataBind();
            return hs;
        }

        /// <summary>
        /// HTML select 绑定扩展
        /// </summary>
        /// <param name="hs">绑定控件</param>
        /// <param name="source">数据源</param>
        /// <param name="text">显示文本</param>
        /// <param name="value">值</param>
        /// <param name="flag">是否加载空项　标识</param>
        /// <returns>绑定后的控件</returns>
        public static HtmlSelect BindSource(this HtmlSelect hs, IEnumerable source, string text, string value, bool flag)
        {
            hs.DataSource = source;
            hs.DataTextField = text;
            hs.DataValueField = value;
            hs.DataBind();

            if (flag)
            {
                hs.Items.Insert(0, new ListItem("---请选择---", ""));
            }
            return hs;
        }
        #endregion

        #region 页面扩展

        public static void Alert(this Page pg, string msg)
        {
            pg.ClientScript.RegisterStartupScript(typeof(string), "alert", "alert('" + msg + "');", true);
        }

        public static void AlertGoto(this Page pg, string msg, string url)
        {
            pg.ClientScript.RegisterStartupScript(typeof(string), "alert", "alert('" + msg + "');window.location.href='" + url + "'", true);
        }

        public static string AppPath(this HttpRequest req)
        {
            var path = req.ApplicationPath;
            if (path.Length == 1)
            {
                return string.Empty;
            }
            return path;
        }

        public static string AppPath(this Page pg)
        {
            return pg.Request.AppPath();
        }

        public static string RegScript(this Page pg, string path)
        {
            string str = "<script type=\"text/javascript\" src=\"{0}\"></script>";
            return string.Format(str, pg.ResolveUrl(path));
        }

        public static string RegStyle(this Page pg, string path)
        {
            string str = "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />";
            return string.Format(str, pg.ResolveUrl(path));
        }

        /// <summary>
        /// 包装$(function () {XXX})
        /// </summary>
        /// <param name="funstr"></param>
        public static void jQueryReady(this Page pg, string funstr)
        {
            string str = @"
$(function () {{
{0}
}});";
            pg.ClientScript.RegisterStartupScript(typeof(string), "jQueryReady", string.Format(str, funstr), true);
        }

        /// <summary>
        /// 页面回车控制
        /// </summary>
        /// <param name="clientid">html标签的id</param>
        public static void KeyEnter(this Page pg, string clientid)
        {
            string str = @"
 $('body').keydown(function (event) {{
                if (event.keyCode == 13) {{
                    $('#{0}').click();
                }}
            }});";
            pg.jQueryReady(string.Format(str, clientid));
        }

        #endregion

    }
}
